﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using KC.Framework.Tenant;
using KC.Service.Core;
using System.Threading.Tasks;

namespace KC.MVC.Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public abstract class WebApiBaseController : Controller
    {
        protected string ServiceName = "KC.MVC.Core.Controllers.WebApiBaseController";
        protected readonly Tenant Tenant;
        protected readonly IServiceProvider ServiceProvider;
        protected readonly ILogger Logger;

        public WebApiBaseController(
            Tenant tenant,
            IServiceProvider serviceProvider,
            ILogger logger)
        {
            Tenant = tenant;
            ServiceProvider = serviceProvider;
            Logger = logger;
        }

        #region 文件地址
        private string _serverPath;
        protected string ServerPath
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_tempDir))
                {
                    var env = (Microsoft.AspNetCore.Hosting.IHostingEnvironment)
                        HttpContext.RequestServices.GetService(
                            typeof(Microsoft.AspNetCore.Hosting.IHostingEnvironment));
                    _serverPath = env.ContentRootPath;
                }
                return _serverPath;
            }
            set { _serverPath = value; }
        }

        private string _tempDir;
        //上传使用
        protected string TempDir
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_tempDir))
                {
                    _tempDir = ServerPath + "/TempDir";
                    if (!Directory.Exists(_tempDir))
                    {
                        try
                        {
                            Directory.CreateDirectory(_tempDir);
                        }
                        catch (SecurityException)
                        {

                        }
                    }
                }
                return _tempDir;
            }
            set { _tempDir = value; }
        }
        #endregion

        #region Get JsonResult

        protected JsonResult ThrowErrorJsonMessage(bool success, string message)
        {
            return Json(new { success = success, message = message });
        }

        protected JsonResult GetServiceJsonResult<T>(Func<T> func)
        {
            var result = ServiceWrapper.Invoke(
                ServiceName,
                func.Method.Name,
                func,
                Logger);
            return Json(result);
        }
        protected async Task<JsonResult> GetServiceJsonResultAsync<T>(Func<Task<T>> func)
        {
            var result = await ServiceWrapper.InvokeAsync<T>(
                ServiceName,
                func.Method.Name,
                func,
                Logger);
            return Json(result);
        }

        protected ServiceResult<T> GetServiceResult<T>(Func<T> func)
        {
            return ServiceWrapper.Invoke(
                ServiceName,
                func.Method.Name,
                func,
                Logger);
        }

        protected async Task<ServiceResult<T>> GetServiceResultAsync<T>(Func<Task<T>> func)
        {
            var result = await ServiceWrapper.InvokeAsync<T>(
                ServiceName,
                func.Method.Name,
                func,
                Logger);
            return result;
        }

        #endregion

        /// <summary>
        /// 获取域名的顶级域名
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        protected static string GetTopDomainName(string domain)
        {
            domain = domain.Trim().ToLower();
            //顶级域名太多了，暂时列出常用的
            string rootDomain = ".com.cn|.gov.cn|.cn|.com|.net|.org|.so|.co|.mobi|.tel|.biz|.info|.name|.me|.cc|.tv|.asiz|.hk";
            if (domain.StartsWith("http://")) domain = domain.Replace("http://", "");
            if (domain.StartsWith("https://")) domain = domain.Replace("https://", "");
            if (domain.StartsWith("www.")) domain = domain.Replace("www.", "");
            //safsd.asdfasdf.baidu.com.cn/ssssd/s/b/d/hhh.html?domain=sfsdf.com.cn&id=1
            if (domain.IndexOf("/") > 0)
                domain = domain.Substring(0, domain.IndexOf("/"));
            //safsd.asdfasdf.baidu.com.cn
            foreach (string item in rootDomain.Split('|'))
            {
                if (domain.EndsWith(item))
                {
                    domain = domain.Replace(item, "");
                    if (domain.LastIndexOf(".") > 0)
                    {
                        domain = domain.Replace(domain.Substring(0, domain.LastIndexOf(".") + 1), "");
                    }
                    return domain + item;
                }
            }
            return "";
        }

    }
}
